#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#include <errno.h>
#include <ctype.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
// #include "listenlib.c"

#define HTTP_BUFFER_SIZE 102400 // 102400 =100 KB


int listen_http(int client_socket, const char *domain, char *buffer) {

    ssize_t buffer_len = 1;

    // 创建套接字连接目标服务器
    printf("my_listen ... host = %s && url= %d \n", domain, client_socket);
    int target_socket = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in target_addr;
    target_addr.sin_family = AF_INET;
    target_addr.sin_addr.s_addr = INADDR_ANY;
    printf("my_listen 000 \n");
    target_addr.sin_port = htons(88);
    int ir = inet_pton(AF_INET, domain, &target_addr.sin_addr);
    // target_addr.sin_port = htons(80);
    // int ir = inet_pton(AF_INET, "admin.hdedu.fun", &target_addr.sin_addr);

    printf("my_listen 111 == %d \n", ir);
    int sock_fd = -1;
    // sock_fd = socket_connect(target_host, target_port, 5);
    sock_fd = connect(target_socket, (struct sockaddr*)&target_addr, sizeof(target_addr));
    if (sock_fd < 0) {
        printf("Error connecting to target server - %d \n", sock_fd);
        close(client_socket);
        exit(EXIT_FAILURE);
    }

     // 接收请求并打印内容
    while ( buffer_len > 0) {
        printf("Received request::: \n%s\n", buffer);
        // memset(buffer, 0, sizeof(buffer));  // 清空缓冲区


        // 往目标服务器发送数据
        ssize_t bytes_sent = send(target_socket, buffer, sizeof(buffer), 0);
        printf("send server_web get send = %zd \n", bytes_sent);
        if ( bytes_sent < 0 ){
            perror("Send failed");
            printf("Get error :%s \n", strerror(errno));
        }

        // 从目标服务器读取响应
        // char *get_buffer = (char *)malloc(1024);
        ssize_t send_res = -1;
        printf("received  server_web start get  = %s \n", buffer);
        ssize_t bytes_received = recv(target_socket, buffer, sizeof(buffer), 0);
        printf("received  server_web get received  = %zd \n", bytes_received);
        if ( bytes_received < 0 ){
            perror("bytes_received failed");
            char* response = "HTTP/1.1 200 OK\r\nContent-Length: 16\r\n\r\nHello World 123!";
            send_res = send(client_socket, response, strlen(response), 0);
        } else {
            send_res = send(client_socket, buffer, bytes_received, 0);
        }
        printf("get response 111 send = %zd ;; received = %zd buffer = %s... \n", bytes_received, send_res, buffer);
        // free(get_buffer);

        buffer_len = recv(client_socket, buffer, HTTP_BUFFER_SIZE, 0);
    }

    // 关闭套接字
    printf("my_listen 555 \n");
    close(client_socket);
    close(target_socket);
    return 0;
}
